<script lang="ts">
    import { onDestroy } from "svelte";
    import { useStyle } from "../utils/useStyle";
    import { toRGBAString } from "./utils";

    const props = $props();
    let left = $state(props.value.hsl.a * 100);

    const gradientStyle = $derived.by(() => {
        const { r, g, b } = props.value.rgba;
        const start = toRGBAString({ r, g, b, a: 0 });
        const finish = toRGBAString({ r, g, b, a: 1 });
        return useStyle({}, { background: `linear-gradient(to right, ${start} 0%, ${finish} 100%)` });
    });

    let container: any;
    const handleMouseDown = (e: any) => {
        if (typeof e.button === "number" && e.button !== 0) return false;
        handleChange(e);

        document.addEventListener("mousemove", handleChange, false);
        document.addEventListener("mouseup", onDragEnd, false);
    };

    const onDragEnd = (e: any) => {
        handleChange(e);
        document.removeEventListener("mousemove", handleChange);
        document.removeEventListener("mouseup", onDragEnd);
    };

    onDestroy(() => {
        document.removeEventListener("mousemove", handleChange);
        document.removeEventListener("mouseup", onDragEnd);
    });

    const handleChange = (e: any) => {
        e.preventDefault();
        e.stopPropagation();

        const { clientWidth } = container;
        const xOffset = container.getBoundingClientRect().left + window.screenX;
        const left = e.clientX - xOffset;
        if (left < 0) {
            change(0);
            return;
        }
        if (left > clientWidth) {
            change(1);
            return;
        }

        change(Math.round((left * 100) / clientWidth) / 100);
    };

    const change = (newAlpha: number) => {
        left = newAlpha * 100;

        const { h, s, l, a } = props.value.hsl;
        if (a !== newAlpha) {
            props.onChange && props.onChange({ h, s, l, a: newAlpha, source: "rgba" });
        }
    };

    $effect(() => {
        left = props.value.hsl.a * 100;
    });
</script>

<div class="cm-color-picker-alpha" bind:this={container}>
    <!-- svelte-ignore a11y_no_static_element_interactions -->
    <div class="cm-color-picker-alpha-wrap" style={gradientStyle} onmousedown={handleMouseDown}>
        <div class="cm-color-picker-alpha-picker" style={`left: ${left}%; top: 0px `}></div>
    </div>
</div>
